package com.kaili.zuul.security;

import com.alibaba.fastjson.JSONObject;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.ResponseData;
import com.kaili.zuul.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class FailureHandler implements AuthenticationFailureHandler {

    @Autowired
    LoginService loginService;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        String name = (String) request.getAttribute("username");//公司编号
        String code = (String) request.getAttribute("code");//公司编号
        String unlock = (String) request.getAttribute("unlock");//这个为1就证明账户已经上锁了
        System.out.println(name);
        Integer countTrans = loginService.getTranslate(name + code);//用户名查询不到数据的时候肯定为空
        //查询系统参数配置标
        String count = (String) request.getAttribute("count");
        //如果参数没有配置默认能错误4次
        if (count == null) {
            count = "4";
        }
        if (count.isEmpty()) {
            count = "4";
        } else {
            //如果输入的不是整数默认为4次
            if (isDigits(count) == false) {
                count = "4";
            }
        }
        PrintWriter out = response.getWriter();
        String msg = "";
        if (unlock != null) {
            if (unlock.equals("1")) {//这个为1就证明账户已经上锁了
                msg = "账户已经锁定,请联系总部解除锁定!!!";
            }
        } else {
            if (countTrans == null) {//证明是账户不存在
                msg = "登录失败!";
            } else {//账户存在密码错误
                if (countTrans < Integer.parseInt(count)) {
                    msg = "登录失败!你还有" + (Integer.parseInt(count) - countTrans) + "次机会";
                } else if (countTrans >= Integer.parseInt(count)) {
                    msg = "登录失败!账户已锁定,请联系总部解除锁定";
                    loginService.updateUnlock(name);
                }

            }
        }
        String s = JSONObject.toJSONString(new ResponseData(msg, CommonStatus.CONTINUE));
        out.write(s);
        out.flush();
        out.close();
    }

    public static boolean isDigits(String str) {
        return str.matches("[-+]?[0-9]*");
    }
}
